package cn.com.platform.web.manage.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.com.easy.dto.MessageDTO;
import cn.com.easy.exception.BusinessException;
import cn.com.easy.permission.model.UserModel;
import cn.com.easy.permission.service.system.urlreserve.anotion.UrlReserveAnotion;
import cn.com.easy.permission.web.controller.BaseController;
import cn.com.easy.utils.PageRequest;
import cn.com.easy.utils.PageRequestUtils;
import cn.com.easy.utils.PageUtils;
import cn.com.easy.utils.ResponseOutputUtils;
import cn.com.platform.dao.AccessoryDao;
import cn.com.platform.entity.AccessoryEntity;
import cn.com.platform.utils.UploadFileUtil;
import cn.com.platform.utils.UploadFileUtil.FileUploadVO;

/**
 * ueditor图片等管理
 * 
 * @author nibili 2017年6月24日
 * 
 */
@Controller
@RequestMapping("/manage/ueditor")
public class UEditorManagerController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(UEditorManagerController.class);
	/** 文件服务类 */
	@Autowired
	private AccessoryDao accessoryDao;

	@UrlReserveAnotion("UeEditorDemo")
	@RequestMapping("/demo")
	public String demo(ModelMap modelMap, HttpServletRequest req, HttpServletResponse res) throws BusinessException {
		return "/manage/ueditor/demo";
	}

	/**
	 * 进入添加图片页面
	 * 
	 * @param modelMap
	 * @param req
	 * @param res
	 * @return
	 * @auth nibili 2018年7月16日
	 */
	// @UrlReserveAnotion("进入添加图片页面")
	@RequestMapping("/photo_add")
	public String addPhotoPre(ModelMap modelMap, HttpServletRequest req, HttpServletResponse res) {
		return "/manage/ueditor/photo_add";
	}

	/**
	 * 编辑器选择图片
	 * 
	 * @param modelMap
	 * @param req
	 * @param res
	 * @param pageRequest
	 * @param albumId
	 * @param id
	 * @return
	 * @throws BusinessException
	 * @auth nibili 2018年7月16日
	 */
	// @UrlReserveAnotion("编辑器选择图片")
	@RequestMapping("/photo_select")
	public String selectImg4editor(ModelMap modelMap, HttpServletRequest req, HttpServletResponse res, PageRequest pageRequest, Long moduleId, Long albumId) {
		try {
			if (moduleId == null) {
				throw new BusinessException("模块id不能为空");
			}
			if (albumId == null) {
				throw new BusinessException("相册id不能为空");
			}
			pageRequest.setPageSize(12);
			org.springframework.data.domain.PageRequest pageReqeust = PageRequestUtils.buildSpringDataPageRequest(pageRequest);
			org.springframework.data.domain.Page<AccessoryEntity> list = null;
			list = accessoryDao.findByModuleIdAndAlbumIdAndDeleteStatus(moduleId, albumId, false, pageReqeust);
			cn.com.easy.utils.Page<AccessoryEntity> page = PageUtils.getPage(list);
			modelMap.addAttribute("page", page);
		} catch (BusinessException ex) {
			modelMap.addAttribute("errorMsg", ex.getLocalizedMessage());
		} catch (Exception e) {
			logger.error("选择图片异常", e);
			modelMap.addAttribute("errorMsg", "选择图片异常");
		}
		return "/manage/ueditor/photo_select";
	}

	/**
	 * 上传文件
	 * 
	 * @param file
	 * @param req
	 * @param res
	 * @param moduleId
	 * @param albumId
	 * @throws Exception
	 * @auth nibili 2018年7月16日
	 */
	// @UrlReserveAnotion("上传文件")
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public void uploadFile(@RequestParam(value = "file") MultipartFile[] file, HttpServletRequest req, HttpServletResponse res, Long moduleId, Long albumId) {
		try {
			if (moduleId == null) {
				throw new BusinessException("模块id不能为空");
			}
			if (albumId == null) {
				throw new BusinessException("相册id不能为空");
			}
			UserModel user = getCurrentUser(req);
			if (user == null) {
				throw new BusinessException("用户获取失败,请重新登录");
			}
			// 商品图片存放路径
			String storageFilePath = "accessory/" + moduleId + "/" + albumId;
			for (int i = 0; i < file.length; i++) {
				FileUploadVO fileUpload = new FileUploadVO();
				fileUpload.setFile(file[i]);
				fileUpload.setStorageFilePath(storageFilePath);
				fileUpload.setStorageFileName(UUID.randomUUID().toString());
				fileUpload.setUserId(user.getId());
				// 上传图片到硬盘和数据库
				AccessoryEntity acc = UploadFileUtil.uploadFile(fileUpload);
				acc.setModuleId(moduleId);
				acc.setAlbumId(albumId);
				// 上传图片到数据库
				accessoryDao.save(acc);

			}
			ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", true, "上传成功"));
		} catch (BusinessException ex) {
			ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", false, ex.getMessage()));
		} catch (Exception e) {
			logger.error("上传图片错误：", e);
			ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", false, "上传图片错误"));
		}
	}
}
